﻿using General.Core.Config;
using General.Core.Data;
using General.Entities.Data;
using General.Entities.Models;
using General.Services.Template;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace General.Services.DiyPage
{
    public class DiyPageService: IDiyPageService
    {
        private readonly IRepository<tc_diypage> tc_DiypageRepository;
        private readonly ITemplateService templateService;
        private readonly IMemoryCache memoryCache;

        public DiyPageService(IRepository<tc_diypage> tc_diypageRepository, 
            ITemplateService templateService,
            IMemoryCache memoryCache)
        {
            tc_DiypageRepository = tc_diypageRepository;
            this.templateService = templateService;
            this.memoryCache = memoryCache;
        }



        /// <summary>
        /// 获取列表信息    
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        public async Task<AdminResult> GetList(int page, int limit, string name)
        {
            AdminResult result = new AdminResult();
            var query = tc_DiypageRepository.Table.Where(x => !string.IsNullOrWhiteSpace(name) ? x.title.Contains(name) : true).OrderByDescending(x => x.id);
            result.count = await query.CountAsync();
            result.data = await query.Skip((page - 1) * limit).Take(limit).ToListAsync();
            result.code = 0;
            return result;
        }

        /// <summary>
        /// 获取所有正常状态页面列表（路由）  
        /// </summary>
        /// <returns></returns>
        public async Task<List<tc_diypage>> GetNormalStausList()
        {
            var result = await tc_DiypageRepository.Table.Where(x => x.status == 1).Select(x=>new tc_diypage()
            {
                 id=x.id, title=x.title, route=x.route
            }).ToListAsync();
            return result;
        }


        /// <summary>
        /// 判断是否有重名路由
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public async Task<bool> IsHasRoute(string name, int? id = null)
        {
            if (id == null)
            {
                return await tc_DiypageRepository.IsExistAsync(x => x.route == name.Trim());
            }
            var model = await tc_DiypageRepository.GetAsync(x => x.id == id);
            return await tc_DiypageRepository.IsExistAsync(x => x.route != model.route && x.route == name);
        }


        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task AddInfo(tc_diypage model)
        {
            model.createTime = DateTime.Now;
            model.updateTime = DateTime.Now;
            await tc_DiypageRepository.insertAsync(model);
        }


        /// <summary>
        /// 后台编辑数据
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public async Task<int> EditInfo(tc_diypage model)
        {
            model.updateTime = DateTime.Now;
            Expression<Func<tc_diypage, object>>[] updatedProperties = {
                    p => p.updateTime,p=>p.description,p=>p.htmlContent,p=>p.isMaster,p=>p.keywords,p=>p.route,p=>p.status,p=>p.title
                };
            return await tc_DiypageRepository.UpdateByFieldsAsync(model, updatedProperties);
        }


        /// <summary>
        /// 批量删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<int> DeleteInfo(string ids)
        {
            var arr = ids.Split(",", StringSplitOptions.RemoveEmptyEntries);
            List<tc_diypage> list = new List<tc_diypage>();
            foreach (var item in arr)
            {
                list.Add(new tc_diypage() { id = Convert.ToInt32(item) });
            }

            return await tc_DiypageRepository.DeleteListByFieldsAsync(list);
        }



        /// <summary>
        /// 获取页面html
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> GetPageHtml(string name)
        {
            if (string.IsNullOrWhiteSpace(name)) {
                return new RedirectToActionResult("404","Error","");
            }
            ContentResult content = new ContentResult();
            content.ContentType = "text/html;charset=utf-8";
            if (WebSiteTemplateConfig.WebSite_OpenDataCache)
            {
                var memoryDataInfo = memoryCache.Get(WebSiteConfig.SYSTEM_DIYPAGEMEMORYKEY_STRING+ name);
                if (memoryDataInfo != null)
                {
                    content.Content = memoryDataInfo.ToString();
                    return content;
                }
            }

            var model = await tc_DiypageRepository.GetAsync(x=>x.route == name);
            if (model == null || model.status != 1)
                return new RedirectToActionResult("404", "Error", "");
            var returnHtml = string.Empty;
            if (model.isMaster == 1)
            {
                returnHtml = await templateService.GetPageHtmlContent("DiyPage");
            }
            else
            {
                returnHtml = model.htmlContent ?? "";
            }
            returnHtml = returnHtml.Replace("@Title", model.title).Replace("@KeyWords", model.keywords).Replace("@Description", model.description);
            if (model.isMaster == 1)
            {
                returnHtml = returnHtml.Replace("@Section_Main", model.htmlContent);
            }
            if (WebSiteTemplateConfig.WebSite_OpenDataCache)
                memoryCache.Set(WebSiteConfig.SYSTEM_DIYPAGEMEMORYKEY_STRING+name, returnHtml);

            content.Content = returnHtml;
            return content;
        }
    }
}
